package guowei.guliauth.controller;

import guowei.common.exception.BizCodeEnume;
import guowei.common.utils.R;
import guowei.guliauth.constant.SmsConstant;
import guowei.guliauth.feign.SmsSendFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 为了验证码60s内不被多次获取
 * 以及注册校验验证码
 */
@Controller
public class SendMsgController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsSendFeign smsSendFeign;

    @ResponseBody
    @GetMapping("/sms/sendMsg")
    public R sendMsg(@RequestParam("phone") String phone){
        //1 接口防刷

        String rediscode = (String) redisTemplate.opsForValue().get(SmsConstant.SMS_PARAM_PREFIX + phone);
        if (!StringUtils.isEmpty(rediscode)){
            Long time1 = Long.valueOf(rediscode.split("_")[1]);
            if (System.currentTimeMillis() - time1 < 60000){
                return R.error(BizCodeEnume.SMS_PARAM_EXCEPTION.getCode(), BizCodeEnume.SMS_PARAM_EXCEPTION.getMsg());
            }
        }
        //2. 验证码再次校验
       String param = String.valueOf(UUID.randomUUID().toString().hashCode())
               .replace("-","").substring(0, 6) + "_" + System.currentTimeMillis();

//       redis缓存验证码 且60s内不能再发验证码
       redisTemplate.opsForValue().set(SmsConstant.SMS_PARAM_PREFIX + phone,param,10, TimeUnit.MINUTES);

       smsSendFeign.sendMsg(phone,param);
       return R.ok();
    }

}
